package com.lungle.warmdiary.app.view.me.fragment;

import android.content.Context;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lungle.warmdiary.R;
import com.lungle.warmdiary.app.AppContext;
import com.lungle.warmdiary.app.api.remote.ApiFactory;
import com.lungle.warmdiary.app.base.BaseFragment;
import com.lungle.warmdiary.app.base.BaseSubscriber;
import com.lungle.warmdiary.app.model.Result;
import com.lungle.warmdiary.app.model.event.TesterApplyStatusChangeEvent;
import com.lungle.warmdiary.app.model.response.TesterStat;
import com.lungle.warmdiary.app.ui.widget.AutoGridView;
import com.lungle.warmdiary.app.ui.widget.AutoListView;
import com.lungle.warmdiary.app.utils.UIHelper;
import com.lungle.warmdiary.app.view.me.adapter.PassAdapter;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by zhangxueyuan on 16/10/5.
 * <p>
 * 应聘亲测师 协议阅读
 * 应聘亲测师 所有申请列表页面
 */
public class TesterStatFragment extends BaseFragment {

    @Bind(R.id.industry_images)
    AutoGridView industryImages;
    @Bind(R.id.apply_has)
    LinearLayout applyHas;
    @Bind(R.id.industry_listview)
    AutoListView industryListview;
    @Bind(R.id.btn_read)
    Button btnRead;

    StateAdapter stateAdapter;
    @Bind(R.id.apply_has_text)
    TextView applyHasText;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(getLayoutId(), container, false);
        initData();
        initView(view);
        return view;
    }


    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(getActivity());

    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(getActivity());

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);

    }

    @Override
    public void initView(View view) {
        ButterKnife.bind(this, view);
        loadTesterStat2();

    }

    @Override
    public void initData() {
        IndustryNum = AppContext.getIndustryNum();
    }

    List<TesterStat> listpass;
    List<TesterStat> listcheck;

    private int IndustryNum;

    private void fillUI() {

        if (list == null || list.size() == 0) {
            applyHasText.setVisibility(View.VISIBLE);
            applyHas.setVisibility(View.GONE);
            applyHasText.setText("亲，您还不是亲测师，赶快去申请一个亲测徽章吧！");
            return;
        } else {
            if (IndustryNum > 0 && list.size() == IndustryNum) {
                btnRead.setVisibility(View.GONE);
            } else {
                btnRead.setVisibility(View.VISIBLE);
                btnRead.setText("继续应聘");
            }
        }

        listpass = new ArrayList<TesterStat>();
        List<TesterStat> listrefuse = new ArrayList<TesterStat>();
        listcheck = new ArrayList<TesterStat>();

        for (TesterStat testerStat : list) {
            if (testerStat.getStatus() == TesterStat.CHECK)
                listcheck.add(testerStat);
            else if (testerStat.getStatus() == TesterStat.PASS)
                listpass.add(testerStat);
            else if (testerStat.getStatus() == TesterStat.REFUSE)
                listrefuse.add(testerStat);
        }

        listcheck.addAll(listrefuse);
        if (listcheck.size() > 0) {
            stateAdapter = new StateAdapter(getActivity(), listcheck);
            industryListview.setAdapter(stateAdapter);
            stateAdapter.notifyDataSetChanged();
            applyHasText.setVisibility(View.GONE);
        }
        if (listpass.size() > 0) {
            applyHasText.setVisibility(View.VISIBLE);
            applyHas.setVisibility(View.VISIBLE);

            applyHasText.setText(Html.fromHtml(String.format("亲，您已经拥有<font color=#F94848>%d</font>个亲测徽章", listpass.size())));
            PassAdapter passAdapter = new PassAdapter(getActivity(), listpass);
            industryImages.setAdapter(passAdapter);
            passAdapter.notifyDataSetChanged();

            if (IndustryNum > 0 && listpass.size() == IndustryNum) {
                applyHasText.setText("亲，您已经拥有全部亲测徽章");
            }
        } else {
            applyHas.setVisibility(View.GONE);
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_tester_stat;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
//        if (industryDAO != null)
//            industryDAO.close();

    }

    List<TesterStat> list;


    private void loadTesterStat2() {
        ApiFactory.getUserApi().getMyTesterStat().subscribeOn(Schedulers.newThread())
                .compose(this.<Result<List<TesterStat>>>bindToLifecycle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<Result<List<TesterStat>>>(getActivity()) {
                    @Override
                    public void onError(Throwable e) {
                        hideWaitDialog();
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        hideWaitDialog();
                    }

                    @Override
                    public void onNext(Result<List<TesterStat>> userResult) {
                        list = userResult.getData();
                        if (list != null && list.size() > 0)
                            for (TesterStat testerStat : list) {

                                testerStat.setName(AppContext.getIndustryName("" + testerStat.getIndustry()));
                                testerStat.setIcon(AppContext.getIndustryUrl("" + testerStat.getIndustry()));
                            }
                        fillUI();
                    }
                });
    }

    @OnClick({R.id.btn_read})
    public void onClick(View view) {
        switch (view.getId()) {


            case R.id.btn_read:

                UIHelper.testerApply(getActivity(), null, list);

                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onStatusChange(TesterApplyStatusChangeEvent appStatusChangeEvent) {
        loadTesterStat2();
    }


    private class StateAdapter extends BaseAdapter {
        private Context mContext;

        List<TesterStat> nums;

        public StateAdapter(Context mContext, List<TesterStat> nums) {
            super();
            this.mContext = mContext;
            this.nums = nums;
        }

        @Override
        public int getCount() {
            return nums.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder vh;
            if (convertView == null || convertView.getTag() == null) {
                convertView = LayoutInflater.from(mContext).inflate(
                        R.layout.list_cell_applystat, parent, false);
                vh = new ViewHolder(convertView);
                convertView.setTag(vh);
            } else {
                vh = (ViewHolder) convertView.getTag();
            }

            final TesterStat item = nums.get(position);
            if (item.getStatus() != 3) {
                vh.imageView.setVisibility(View.GONE);
                vh.industryText.setText(String.format("%s徽章申请已提交，审核状态中", item.getName()));
                vh.industryText.setTextColor(0xFF666666);
                convertView.setOnClickListener(null);
            } else if (item.getStatus() == 3) {
                vh.imageView.setVisibility(View.VISIBLE);
                vh.industryText.setText(String.format("%s徽章申请未通过", item.getName()));
                vh.industryText.setTextColor(0xFFF94848);
                convertView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                        UIHelper.showTesterIndustry(this, industryid, REQUEST_INDUSTRY, null);
                        UIHelper.testerApply(getActivity(), item, list);
                    }
                });
            }

            return convertView;
        }

    }

    static class ViewHolder {
        @Bind(R.id.industry_text)
        TextView industryText;
        @Bind(R.id.imageView)
        ImageView imageView;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
